package selenium;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class tiKuanJS2 {
	// 网易基本成型 帐号文件为E:\\ZhangHao/娱乐号.txt
	@SuppressWarnings("resource")
	public static void main(String[] args) throws Exception {
		tiKuanJS2 tiKuanJSDemo = new tiKuanJS2();
		tiKuanJSDemo.doTiKuan();
	};

	public void doTiKuan() throws Exception {
		String zhangHaoLeixing = "影视号";// 文件夹和账户名都是这个
		SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Date currentTime = new Date();
		String dateString = format1.format(currentTime);
		String zhangHaofilepath = "D:/java/帐号/" + "开收益";// 帐号文件夹路径
		File zhangHaofile = new File(zhangHaofilepath);
		if (!zhangHaofile.exists()) {
			zhangHaofile.mkdirs();
		}
		File zhangHaoExist = new File(zhangHaofilepath + "/" + dateString + ".txt");// 读视频文件
		if (!zhangHaoExist.exists()) {
			List<String> listFile = readFileAll(
					this.getClass().getResource("/").getPath() + "/" + zhangHaoLeixing + ".txt");
			writeFile(zhangHaofilepath + "/" + dateString + ".txt", listFile);
		}

		Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");
		Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe");
		final WebDriver driver = new ChromeDriver();
		Point targetPosition = new Point(2600, 300);
		driver.manage().window().setPosition(targetPosition);
		driver.manage().window().maximize();
		driver.get("http://mp.163.com/wemedia/baseinfo/isexist/1");
		JavascriptExecutor js = (JavascriptExecutor) driver;
		try {
			for (int z = 0; z < 99999; z++) {
				System.out.println(z + "----" + z + "----" + z);
				driver.manage().deleteAllCookies();

				SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy hh:mm:ss a", Locale.US);

				String name = "NTES_SESS";
				// 读取帐号文件

				List<String> zhanghus = readFileAll(zhangHaofilepath + "/" + dateString + ".txt");
				if (zhanghus.size() < 1) {
					System.out.println("没账户了");
					Date currentNewTime = new Date();
					String dateNewString = format1.format(currentNewTime);
					File zhangHaoNewExist = new File(zhangHaofilepath + "/" + dateNewString + ".txt");// 读视频文件
					if (!zhangHaoNewExist.exists()) {
						throw new RuntimeException();
					}
				}
				String zhangHu = zhanghus.get(0).trim();

				String[] s1 = zhangHu.split("\\/", -1);

				String value = s1[4];
				System.out.println(s1[0] + "----" + s1[1] + "----【" + s1[2] + "】----开始执行任务");

				String domain = ".mp.163.com";
				String path = "/";
				Date expiry = sdf.parse("1/30/2028 10:31:37 AM");
				Cookie cookie = new Cookie(name, value, domain, path, expiry);
				driver.manage().addCookie(cookie);
				Thread.sleep(300);
				for (int i = 0; i < 999; i++) {
					driver.get("https://www.baidu.com/");
					try {
						driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
						driver.get("http://mp.163.com/profit/incomePage.html");
						break;
					} catch (Exception e2) {
						System.out.println("请求发生故障,从头再来");
						continue;
					}
				}

				Thread.sleep(40);
				WebElement tiKuanElement = driver.findElement(By.xpath("//*[@id='income-cash']"));
				js.executeScript("arguments[0].removeAttribute('disabled')", tiKuanElement);
				js.executeScript("arguments[0].click();", tiKuanElement);
				Thread.sleep(400);
				
				WebElement tiKuanTipElement = driver.findElement(By.xpath("/html/body/div[4]/div[2]/div/div[1]/h4"));
				if("收入提取".equals(tiKuanTipElement.getText())){
					WebElement btn_okElement = driver.findElement(By.className("js-btn-ok"));
					js.executeScript("arguments[0].click();", btn_okElement);
					System.out.println("等待【跳过弹窗】");
					//*[@id="desc"]
					WebElement descElement = driver.findElement(By.xpath("//*[@id='desc']"));
					String renmingbi = descElement.getAttribute("value");
					System.err.println("----"+renmingbi+"元人民币提取成功----");
				}
				
				// **************等待时间****************
				/*
				 * WebDriverWait wait = new WebDriverWait(driver, 5000);
				 * //**************等待时间**************** wait.until(new
				 * ExpectedCondition<WebElement>() {
				 * 
				 * @Override public WebElement apply(WebDriver d) { WebElement
				 * ddElement = driver.findElement(By.className("isActive")); if
				 * (ddElement.getText().equals("跟贴管理")) { return ddElement; }
				 * else { return null; } } });
				 */
				// **************等待时间****************

				// 删除帐号第一行
				List<String> listZhangHao = readFile(zhangHaofilepath + "/" + dateString + ".txt", zhangHu);
				writeFile(zhangHaofilepath + "/" + dateString + ".txt", listZhangHao);
				driver.manage().deleteAllCookies();
				System.out.println("还有(" + listZhangHao.size() + ")个【帐号】没有传输完");
				System.err.println("结束时间-【" + format0.format(new Date()) + "】");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		driver.quit();

	}

	// 方法1：

	public void method1() {
		FileWriter fw = null;
		try {
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File("E:\\dd.txt");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println("追加内容");
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 方法2：

	public static void method2(String file, String conent) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out.write(conent + "\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	// 方法3：

	public static void method3(String fileName, String content) {
		try {
			// 打开一个随机访问文件流，按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
			// 文件长度，字节数
			long fileLength = randomFile.length();
			// 将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content + "\r\n");
			randomFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static List<String> readFile(String filePath, String str) throws IOException {
		File file = new File(filePath);
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		reader = new BufferedReader(new FileReader(file));
		String text = reader.readLine();
		while (text != null) {
			if (!text.trim().equals(str)) {
				list.add(text + "\r\n");
			}
			text = reader.readLine();
		}
		reader.close();
		return list;
	}

	public static List<String> readFileAll(String filePath) throws IOException {
		File file = new File(filePath);
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		reader = new BufferedReader(new FileReader(file));
		String text = reader.readLine();
		while (text != null) {
			list.add(text.trim() + "\r\n");
			text = reader.readLine();
		}
		reader.close();
		return list;
	}

	public static void writeFile(String filePath, List<String> list) throws IOException {
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream outputStream = new FileOutputStream(file);
		for (String s : list) {
			outputStream.write(s.getBytes());
		}
		outputStream.close();
	}

}
